package org.example.hello6_messageAck;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import sun.font.TrueTypeFont;

import java.io.IOException;

@Component
@Slf4j
public class Receiver {

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "mac_id", durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = "data", type = ExchangeTypes.DIRECT), key = "mac_key"))
    @RabbitHandler
    public void receivedHomeMac(Message message, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel)
            throws IOException {

        boolean result = true;
        try {
            log.info("数据接收成功:{}", message);
        } catch (Exception e) {
            log.error("数据同步异常:{}", e.toString());
            result = false;
        }
        if (result) {
            // RabbitMQ的ack机制中，第二个参数返回true，表示需要将这条消息投递给其他的消费者重新消费（不用改）
            channel.basicAck(deliveryTag, false);

        } else {
            /**
             * 参数说明：
             *
             * 参数一：要签收的投递ID是多少
             * 参数二：是否批量签收
             * 参数三：true;拒绝签收并将消息重新放回消息队列里面    false；拒绝签收，消息不放回消息队列里面
             */
            channel.basicNack(deliveryTag, false, true);
        }
    }
}
